<template>
  <div class="index">
    <van-loading v-if="loading" type="spinner" color="#3875C6" vertical style="position: relative; top: 40%"
      >请稍候，正在打开...</van-loading
    >
    <van-button v-else type="primary" round style="width: 130px; position: relative; top: 40%" @click="scanCode"
      >点击扫一扫</van-button
    >
    <!-- <van-field v-model="barcode" label="文本" placeholder="请输入用户名" />
    <van-button type="primary" @click="toConsumeInfo">去耗材详情</van-button> -->
  </div>
</template>

<script>
import { useRouter } from 'vue-router'
import { getAssetsImages } from '@/utils'
import { reactive, toRefs, onBeforeMount } from 'vue'
import { getSign } from '@/utils/jssdk'
import * as ww from '@wecom/jssdk'
export default {
  setup() {
    const router = useRouter()
    const getAssetsImages1 = getAssetsImages
    const state = reactive({
      barcode: '',
      loading: false
    })
    onBeforeMount(() => {
      state.loading = true
      getSign().then(() => {
        setTimeout(() => {
          scanCode()
        }, 0)
      })
    })
    const scanCode = () => {
      setTimeout(() => {
        state.loading = false
      }, 1000)
      ww.scanQRCode({
        needResult: 1, // 默认为0，扫描结果由企业微信处理，1则直接返回扫描结果
        scanType: ['qrCode', 'barCode'],
        success: function (res) {
          // 当needResult为1时返回处理结果
          const resultStr = res.resultStr
          resultStr.split('&').map((item) => {
            if (item.indexOf('barcode') > -1) {
              state.barcode = item.split('=')[1]
            }
          })
          state.loading = false
          toConsumeInfo()
        },
        fail: function (err) {
          state.loading = false
          if (err.errMsg.includes('scanQRCode: fail cancel')) {
            console.log('用户取消了扫描')
            // 用户取消扫描时的处理逻辑
          } else {
            console.log('扫描失败', err)
            // 其他扫描失败的处理逻辑
          }
          // const msg = 'scanQRCode fail1' + JSON.stringify(err)
          // alert(msg)
        }
      })
    }
    const toConsumeInfo = () => {
      router.push({
        path: '/consumeInfo',
        query: {
          barcode: state.barcode
        }
      })
    }

    return {
      ...toRefs(state),
      scanCode,
      toConsumeInfo,
      getAssetsImages1
    }
  }
}
</script>
<style lang="less" scoped>
.index {
  height: 100%;
  padding: 0 15px;
  text-align: center;
}
</style>
